package com.fs.uc.filter;

import com.fs.uc.base.MyResponse;
import com.fs.uc.base.exception.AuthException;
import com.fs.uc.security.Auth;
import com.fs.uc.security.AuthContext;
import com.fs.uc.security.JwtUserInfo;
import com.fs.uc.security.JwtUtil;
import io.quarkus.runtime.annotations.RegisterForReflection;
import io.smallrye.jwt.auth.principal.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Priority;
import javax.inject.Inject;
import javax.ws.rs.container.*;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

/**
 * @author 崔超
 * 2021/12/3
 */
@Auth
@Priority(2)
@Provider
@RegisterForReflection
public class AuthFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Inject
    JwtUtil jwtUtil;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String token = requestContext.getHeaderString("Authorization");
        if (token == null) {
            throw new AuthException("请求没有携带令牌");
        }
        try {
            JwtUserInfo userInfo = jwtUtil.getUserInfo(token);
            AuthContext.setSubjectId(userInfo.subjectId);
            AuthContext.setSubjectType(userInfo.subjectType);
        } catch (ParseException e) {
            throw new AuthException("令牌检查不正确");
        }
    }

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        AuthContext.destroy();
    }
}
